﻿@model Article
@{
    Layout = "_Layout-Full";
    ViewBag.Title = $"{(Model == null || Model?.Id == 0 ? "发布" : "编辑")}文章";
    var categoriesListItem = ViewData["CategoryList"] as IEnumerable<SelectListItem>;
    var btnClass = "btn btn-light border";
}
<form method="post" class="form-horizontal">
    @if (ViewContext.ModelState.ErrorCount > 0)
    {
        <div asp-validation-summary="ModelOnly" class="alert alert-danger"></div>
    }
    @Html.HiddenFor(m => m.Id)
    @Html.Hidden("UserId", User.Identity.UserId(), null)
    <div class="form-group">
        <div class="row">
            <div class="col-2">
                <select class="form-control" asp-for="CategoryId" asp-items="categoriesListItem"></select>
            </div>
            <div class="col-8">
                <input type="text" class="form-control" asp-for="Title" placeholder="标题" maxlength="60" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="col-2">
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary" onclick="return checkBeforeSubmit()" title="保存并提交"><i class="fa fa-save"></i></button>

                    <button type="button" class="btn btn-dark" title="设置" onclick="toggleSetting()"><i class="fa fa-cogs"></i></button>
                    <a asp-action="List" class="btn btn-info" title="返回列表页"><i class="fa fa-undo"></i></a>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group" id="setting" style="display:none">
        <div class="d-flex justify-content-end">
            <div class="p-1">
                <label asp-for="ViewCount" class="col-form-label"></label>
            </div>
            <div class="p-1">
                <input asp-for="ViewCount" class="form-control  form-control-sm text-center" style="width:80px;" min="0"/>
            </div>
            <div class="p-1">
                <label asp-for="DisplayOrder" class="col-form-label"></label>
            </div>
            <div class="p-1">
                <input asp-for="DisplayOrder" class="form-control form-control-sm text-center" style="width:80px;"/>
            </div>
            <div class="p-2">
                <label class="checkbox-inline">
                    <input asp-for="IsRecommand" /> 推荐
                </label>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="btn-group">
            <button type="button" class="@btnClass" onclick="newDoc()" title="新文档"><i class="fa fa-file"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('# ')" title="插入H1"><i class="fa fa-heading"></i><sub><strong>1</strong></sub></button>
            <button type="button" class="@btnClass" onclick="insertEditor('## ')" title="插入H2"><i class="fa fa-heading"></i><sub><strong>2</strong></sub></button>
            <button type="button" class="@btnClass" onclick="insertEditor('### ')" title="插入H3"><i class="fa fa-heading"></i><sub><strong>3</strong></sub></button>
            <button type="button" class="@btnClass" onclick="insertEditor('#### ')" title="插入H4"><i class="fa fa-heading"></i><sub><strong>4</strong></sub></button>

            <button type="button" class="@btnClass" onclick="insertEditor('**','**')"><i class="fa fa-bold"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('*','*')"><i class="fa fa-italic"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('> ')" title="引用"><i class="fa fa-quote-left"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('* ')" title="无序列表"><i class="fa fa-list-ul"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('\n----')" title="分割线">—</button>

            <button type="button" class="@btnClass" onclick="insertEditor('```\n这里插入代码\n```')" title="插入代码"><i class="fa fa-code"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('[链接文字](超链接url) ')" title="插入超链接"><i class="fa fa-link"></i></button>
            <button type="button" class="@btnClass" onclick="insertEditor('![图片文字](图片url) ')" title="插入图片"><i class="fa fa-image"></i></button>

            <button type="button" class="@btnClass active" onclick="switchSeperator(this)" title="显示预览面板"><i class="fa fa-columns"></i></button>
        </div>
        <div class="clearfix"></div>
        <div class="row">

            <div class="col-6" id="col-content">
                <textarea id="@Html.IdFor(m=>m.Content)" placeholder="支持 Markdown 语法" asp-for="Content" class="form-control" rows="30"></textarea>
            </div>
            <div class="markdown-body col border" style="padding:10px;word-break:break-all;word-wrap:break-word;max-width:50%;overflow-x:hidden;overflow-y:scroll">
                @Model?.Content
            </div>
        </div>
    </div>
</form>
@section styles{
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/vs.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/addon/hint/show-hint.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/fullscreen.css" rel="stylesheet">
    <style type="text/css">
        .CodeMirror { background-color: #eee; height: auto; padding: 20px; font-size: 14px; }

        .CodeMirror-scroll { height: 500px; overflow-y: auto; overflow-x: auto; }
    </style>
}
@section scripts{
    @Html.Partial("/Pages/Shared/_ValidationScripts.cshtml")
    <environment include="Development">
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.js"></script>
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/placeholder.js"></script>
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/fullscreen.js"></script>
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/mode/markdown/markdown.js"></script>
        <script src="https://cdn.bootcss.com/marked/0.3.12/marked.js"></script>
        <script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
    </environment>
    <environment include="Production">
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.min.js"></script>
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/placeholder.min.js"></script>
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/fullscreen.min.js"></script>
        <script src="https://cdn.bootcss.com/codemirror/5.34.0/mode/markdown/markdown.min.js"></script>
        <script src="https://cdn.bootcss.com/marked/0.3.12/marked.min.js"></script>
        <script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
    </environment>
    <script type="text/javascript">
        $(function () {
            $('.markdown-body').css({ 'height': $('.CodeMirror').outerHeight() + 'px' });
            
        })

        var content = document.getElementById('@Html.IdFor(m=>m.Content)');



        var editor = CodeMirror.fromTextArea(content, {
            mode:'markdown',
            lineWrapping: true,
            extraKeys: {
                "Enter": "newlineAndIndentContinueMarkdownList" ,
                "F11": function (cm) {
                    cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                },
                "Esc": function (cm) {
                    if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                }
            }
        });

        editor.on('change',markedHandler);

        var markedRender = new marked.Renderer();
        marked.setOptions({
            renderer: markedRender,
            gfm: true,
            tables: true,
            breaks: true,  // '>' 换行，回车换成 <br>
            pedantic: false,
            sanitize: true,
            smartLists: true,
            smartypants: false
        });

        function markedHandler(codeMirror, changes) {
            var value = codeMirror.getValue()
            $('.markdown-body').html(marked(value));
            $('.markdown-body pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });

            $('#@Html.IdFor(m=>m.Content)').val(value);
        }

        function checkBeforeSubmit() {
            var content = $('#@Html.IdFor(m=>m.Content)').val();
            if (content.length == 0) {
                alert('正文不能是空');
                return false;
            }
            return true;
        }
    @if (Model?.Id > 0)
        {
                                <text>
        markedHandler(editor);
        </text>
        }

        /**
         * 向编辑器插入内容
         * start: 选择的文字前面插入的字符串
         * end: 选择的文字后面插入的字符串，可选则插入空字符串
         */
        function insertEditor(start, end) {
            if (!end) {
                end = '';
            }
            var selection = editor.getSelection();
            if (selection.length == 0) {
                start = '\r' + start;
            }
            var text =start + selection + end;
            editor.replaceSelection(text)
        }

        /**
         * 新文档
         */
        function newDoc() {
            var canClear = true;
            
            if (editor.getValue().length > 0) {
                if (!confirm('当前文档中有内容，确定要清空吗？')) {
                    canClear = false;
                }
            }
            if (canClear) {
                editor.setValue('');
            }
        }

        /**
         * 切换列
         * btn: 当前点击的按钮对象
         */
        function switchSeperator(btn) {
            var previewShown = $(btn).hasClass('active');//是否已经显示了预览面板
            if (previewShown) {
                $(btn).removeClass('active');
                $('#col-content').removeClass('col-6').addClass('col-12');
                $('.markdown-body').addClass('d-none');
            } else {
                $(btn).addClass('active');
                $('#col-content').addClass('col-6').removeClass('col-12');
                $('.markdown-body').removeClass('d-none');
            }
        }

        function toggleSetting() {
            $('#setting').slideToggle(500);
        }
    </script>
}